package com.hy.ai.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hy.ai.entity.po.ChatSession;
import com.hy.ai.mapper.ChatSessionMapper;
import com.hy.ai.repository.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;

@Component
@RequiredArgsConstructor
public class InMemoryChatHistory implements ChatHistoryRepository {

    private final ChatSessionMapper chatSessionMapper;
    private final StringRedisTemplate redisTemplate;

    @Override
    public void save(String type, String chatId, String userId) {
        String key = type + ":" + userId;

        // 检查数据库是否已存在
        QueryWrapper<ChatSession> wrapper = new QueryWrapper<ChatSession>()
                .eq("type", type)
                .eq("chat_id", chatId)
                .eq("user_id", userId);
        Long count = chatSessionMapper.selectCount(wrapper);
        if (count > 0) {
            return; // 已存在
        }

        // 插入数据库
        ChatSession session = new ChatSession()
                .setUserId(Long.parseLong(userId))
                .setType(type)
                .setChatId(chatId)
                .setCreateTime(LocalDateTime.now());
        chatSessionMapper.insert(session);

        // 写入 Redis List（新记录插入前面）
        redisTemplate.opsForList().leftPush(key, chatId);

        // 限制最多缓存 100 条记录（避免列表过长）
        redisTemplate.opsForList().trim(key, 0, 99);

        // 设置过期时间（可选）
        redisTemplate.expire(key, Duration.ofHours(2));
    }


    @Override
    public List<String> query(String type, String userId) {
        String key = type + ":" + userId;

        // 1. 先查 Redis
        List<String> chatRedisIds = redisTemplate.opsForList().range(key, 0, -1);
        if (!chatRedisIds.isEmpty()) {
            return chatRedisIds;
        }

        // 2. 缓存未命中，查数据库
        System.out.println("列表查询缓存未命中");
        QueryWrapper<ChatSession> wrapper = new QueryWrapper<ChatSession>()
                .eq("type", type)
                .eq("user_id", userId)
                .orderByDesc("create_time");

        List<ChatSession> sessions = chatSessionMapper.selectList(wrapper);
        List<String> chatIds = new ArrayList<>();
        for (ChatSession session : sessions) {
            chatIds.add(session.getChatId());
        }

        // 3. 写入 Redis（保持倒序）
        if (!chatIds.isEmpty()) {
            Collections.reverse(chatIds); // 变为旧→新，然后 leftPushAll 得到新→旧
            redisTemplate.opsForList().leftPushAll(key, chatIds);
            redisTemplate.expire(key, Duration.ofHours(2));
        }

        return chatIds;
    }

}
